import { _ } from 'meteor/underscore';
import { JoinClient } from 'meteor-publish-join';
import { Friends } from '/imports/models/Friends';

Template.messages_search.onCreated(function() {
  this.query = new ReactiveVar({});
  this.limit = new ReactiveVar(15);
  this.searchText = new ReactiveVar();

  this.autorun(() => {
    this.resultSub = this.subscribe('get.friends', { user_id: Meteor.userId() }, this.limit.get());
    this.total = JoinClient.get('get.friends.counts');
  });
});

Template.messages_search.onRendered(function() {
  let ps = new PerfectScrollbar('#messages-search-ps');

  $('#messages-search-ps').on('ps-y-reach-end', _.throttle(() => {
    let lmt = this.limit.get();

    if (this.total >= lmt) {
      this.limit.set(lmt + 15);
    }
  }, 200));
});

Template.messages_search.helpers({
  results: function() {
    return Friends.find(Template.instance().query.get(), {
      limit: Template.instance().limit.get(),
      sort: { createdAt: 1 }
    });
  },
  
  loading: function() {
    return !Template.instance().resultSub.ready();
  }
});

Template.messages_search.events({
  'input #messages-search-input'(event, instance) {
    instance.searchText.set(event.target.value);
    let searchText = $.trim(instance.searchText.get());
    if (!searchText || searchText.length === 0) {
      instance.query.set({});
    } else {
      instance.query.set({
        'info.username': { $regex: new RegExp(searchText) }
      });
    }
  }
});
